<?php
class NodeAction extends CommonAction {
	function index(){
		
		//dump(D('Node') -> getListToArray2());exit;
        $id=(int)$this->_get('id');
		$this->list=D('Node')->getList(0,0,$id);
		$this->display();
	}
	
	 
	public function add(){ 
		$this->pid = $this->_get('pid');
		$this->level = $this->_get('level');
		$this->s_gid=M('Menugroup')->select();
		$this->s_pid=D('Node')->getList();
		parent::add();
	}
	
	public function insert(){
	    $map['level'] = $this->_post('level');
		$map['pid'] = $this->_post('pid');
		$map['name'] = $this->_post('name');
		$node = $this->dao -> where($map) -> find();
		if($node){
			$this->error('该节点已经存在！');
		}else{
		    parent::insert();
		}
    }
	
	
	function indextree(){
		$this->listmap = '1';
		$pid = $this->_get('pid') ? $this->_get('pid') : 0;
		$this->listmap.=" and pid=".$pid;
		$this->listorder = 'sort';
		if($this->_param('keywords')){
			$keywords=$this->_param('keywords');
			$_GET['keywords']=urlencode($this->_param('keywords'));
			$this->listmap.=" and (title like '%{$keywords}%' or name like '%{$keywords}%')";
			$this->keywords=$keywords;
		}
		
		$this->initView();
        parent::_list();
		$list=$this->list;
		
		//$this->assign('list',$list);
		$str = $this->fetch();
		$list = $this->view -> get('list');
		foreach($list as $k => $v){
			$str = str_replace('<!--sub#'.$v['id'].'-->', $this->treehtml($v['id']), $str);
		}
		
		$list = $_GET['list'];
		$empty = 1;
		$statu=$list?1:0;
		if($this->get('list')){
			$empty = 0;
		}
		
		die(json_encode(array('empty' => $empty,'tbody'=>$str,'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this-> view -> get('pages'))));
	}
	
	private function treehtml($pid = 0){
		$this->list = $this->dao -> where(array('pid' => $pid)) -> select();
		$curstr = $this->fetch('indextree');
		foreach($this->list as $k => $v){
		   $curstr = str_replace('<!--sub#'.$v['id'].'-->', $this->treehtml($v['id']), $curstr);
		}
		return $curstr;
	}
	
	private function parsesortdata($arr = array(), $ret = array(), $pid = 0){
		$pid1 = $pid;
		foreach($arr as $k => $v){
			$p['pid'] = $pid1;
			$p['id'] = $v['id'];
			$ret[] = $p;
			if(isset($v['children'])){
				$pid = $v['id'];
				$ret = $this->parsesortdata($v['children'], $ret, $pid);
			}
		}
		return $ret;
	}
	
	public function updatesort($data){
		$data = $this->parsesortdata(json_decode($_POST['data'], true));
		foreach($data as $k => $v){
			$map['id'] = $v['id'];
			
			$data['sort'] = $k + 1;
			$data['pid'] = $v['pid'];
			$this->dao -> where($map) -> save($data);
		}
	}
	
	
	public function edit(){ 
		$this->s_pid=D('Node')->getList();
		$this->s_gid=M('Menugroup')->select();
		parent::edit();
	}
	
}
